package qe.spider.grab;

import cn.hutool.core.text.UnicodeUtil;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import qe.spider.vo.PlateList;
import qe.spider.vo.Stock;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;


//查股网-Login，获取Cookie
@Slf4j
public class GrabGubit_Login {
    private String user;

    private String password;

    public GrabGubit_Login(String user, String password) {
        this.user = user;
        this.password = password;
    }

    public GrabGubit_Login() {
        this("xiefeifeihu", "Abc123123");
    }

    public static void main(String[] args) throws IOException {
        new GrabGubit_Login().grab();
        new GrabGubit_ClearZiXuan().grab();
        List<String> codes = List.of("600266", "603721");
        new GrabGubit_AddZiXuan().grab(codes);
        List<Stock> stocks = new GrabGubit_ZhangDieTing(codes).grab();
        log.debug("5日内涨跌停股票{}", stocks);
        stocks = new GrabGubit_ZhangDieTing(codes).grab_ZiXuan();
        log.debug("5日内涨跌停股票{}", stocks);
    }

    private FormBody formBody() {
        FormBody formBody = new FormBody.Builder()
                .add("t", "0")
                .add("user", this.user)
                .add("password", this.password)
                .add("d", "3").build();
        return formBody;
    }

    public void grab() throws IOException {
        OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder()
                .url("http://ddx.gubit.cn/chklogin.php")
                .header("Accept", "*/*")
                .header("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6")
                .header("Cache-Control", "no-cache")
                .header("Connection", "keep-alive")
                .header("Content-Type", "application/x-www-form-urlencoded")
                .header("Dnt", "1")
                .header("Host", "ddx.gubit.cn")
                .header("Origin", "http://ddx.gubit.cn")
                .header("Pragma", "no-cache")
                .header("Referer", "http://ddx.gubit.cn/zixuan.php")
                .post(formBody())
                .build();
        Gson gson = new Gson();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

            List<String> cookies = response.headers("Set-Cookie");
            for (String c : cookies) {
                for (String s : c.split(";")) {
                    String[] cc = s.split("=");
                    GrabGubit.cookies.put(cc[0], cc[1]);
                }
            }

            log.info("选股网Cookie : {}", GrabGubit.cookies);
            String result = UnicodeUtil.toString(response.body().string());
            log.info("登录返回：{}", result);
        }

    }
}
